(function() {
    "use strict";
    window.Sugar = function () {

        this.getCookie = function (field) {
            var stlist = document.cookie.split(";");
            var once;
            var swaplist;
            for (once in stlist) {
                swaplist = stlist[once].split("=");
                if (swaplist[0].replace(/(^\s+)|(\s+$)/g,"") == field) {
                    return swaplist[1];
                }
            }
            return null;
        }
        this.setCookie = function (name, value, expiredays) {
            var exdate = new Date()
            exdate.setDate(exdate.getDate() + expiredays)
            document.cookie = name + "=" +
                decodeURIComponent(value) +
                ((expiredays == null) ? "" : ";expires=" +
                    exdate.toGMTString());
            return (this.getCookie(name) != null);
        };

        this.isset = function(val) {
            return ! (typeof(val) === "undefined");
        };

        this.call = function(json) {
            if (window.XMLHttpRequest)
                var xhr = new XMLHttpRequest();
            else
                var xhr = new ActiveXObject("Microsoft.XMLHTTP");
            xhr.onerror = function(e) {
                console.log('sugar request failed');
                console.log(e);
            }
            xhr.ontimeout = function() {
                throw new Error('sugar request timeout');
            }
            xhr.onprogress = this.isset(json.progress) ? json.progress : false;
            var dStr = "";
            let datakey;
            for (datakey in json.data) {
                dStr += "&"+ datakey+ "="+ json.data[datakey];
            }
            var method = json.method.toUpperCase();
            if (method == "GET") {
                /**
                 * assembling url params
                 */
                if (json.url.indexOf("?") < 0) {
                    json.url = json.url + "?" + dStr.substr(1);
                } else {
                    json.url = json.url + dStr;
                }
            }
            xhr.open(method, json.url, true);
            try {
                xhr.withCredentials = json.withCookie == false ? false : true;
            } catch (e) {
                xhr.withCredentials = false;
            }
            var defaultType = "application/x-www-form-urlencoded;charset=UTF-8";
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", defaultType);
            xhr.responseType = this.isset(json.type) ? json.type: "text";
            let key;
            for (key in json.headers) {
                xhr.setRequestHeader(key, json.headers[key]);
            }
            if (method == "GET") {
                xhr.send(null);
            } else {
                let subst = dStr;
                xhr.send(subst);
            }
            var that = this;
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        if (json.cover) {
                            that.cover("off");
                        }
                        let calldata = that.isset(xhr.response) ? xhr.response : xhr.responseText;
                        json.success(calldata);
                        return 0;
                    }
                }
            }
        };
        
        this.query = function(name) {
            let reg = new RegExp("(^|&)"+ name+ "=([^&]*)(&|$)", "i");
            let swap = window.location.search.substr(1).match(reg);
            return (swap != null) ? unescape(swap[2]) : null;
        }

        this.getNode = function(nodeStr) {
            document.createTextNode
            return document.querySelectorAll(nodeStr);
        }
        this.createNode = function(nodeStr) {
            let nodeSign = nodeStr.substr(0, 1);
            let node = null;
            if (nodeSign === "#") {
                node = document.createElement("div");
                node.id = nodeStr.substr(1, nodeStr.length);
            } else if (nodeSign === ".") {
                node = document.createElement("div");
                node.className = nodeStr.substr(1, nodeStr.length);
            } else {
                node = document.createElement(nodeStr);
            }
            return node;
        }
        this.style = function(node, cssJson) {
            let key;
            let swap = "";
            for (key in cssJson) {
                swap += key+ ":"+ cssJson[key]+ ";";
            }
            node.style.cssText += ";"+ swap;
        }
    };

    window.$ = window.Sugar;
})();